<?php

// +----------------------------------------------------------------------
// | 功能说明"
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2030 http://www.jmzh1688.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: lxl
// +----------------------------------------------------------------------


namespace app\admin\controller;

use think\Controller;
use think\Db;


use app\admin\model\LogActionModel;
use app\admin\model\SysMenuModel;
use app\admin\model\SysRoleModel;

class Base extends Controller
{

    public function _initialize()
    {

        if(empty(session('username')) || empty(session('id')) || empty(session('roleid')) || empty(session('name')) ){
            $Url = url('login/index');
            if(request()->isAjax()){
                return msg(111, $Url, '没有登录');
            }
            $this->redirect($Url);
            return;
        }
     

        if($this->isCheckPermit()==false)
        {

            $Url = url('error/400');
            if(request()->isAjax()){
                return msg(111, $Url, '没有权限');
            }
            $this->redirect($Url);
            return;

        }
    
        self::WriteLog(); //记录日志
    }


    function loadclass()
    {
       
        $tablename = input("get.tablename");
        $flag = input("get.flag");
        $level = input("get.level");
        $valuename = input("get.valuename");
        $parentid = input("get.parentid");

        if($tablename==""){$tablename="sys_dic";}


        if($level==0)
        {
            if($flag=='')
            {
                $list=  Db::name($tablename)->where(['isdelete' =>0])->select();
            }
            else
            {
                $list=  Db::name($tablename)->where(['isdelete' =>0,'flag' =>$flag])->select();
            }
           
        }else{

            if($flag=='')
            {
                $list=  Db::name($tablename)->where(['parentid' =>$parentid])->select(); //'level' =>$level,
            }
            else
            {
                $list=  Db::name($tablename)->where(['flag' =>$flag,'parentid' =>$parentid])->select();//'level' =>$level,
            }

         
        }
       
             if(!array_key_exists("name",$list[0])&&!array_key_exists("title",$list[0]))
         {
         	  $keys=[];foreach ($list[0] as $key => $valuse){$keys[] = $key;} $mykey=$keys[1];
         	 
       
         	for($p=0;$p<count($list);$p++)
         	{
         		$list[$p]["name"]=$list[$p][$mykey];
         	}
         }
       
       
       return json($list);
    }
    

    //如果在菜单中，但没有勾选，则表示无权限。
    //没有在菜单中的接口，则认为是有权限的，且必须控制器中至少有一项含有功能。
    private function isCheckPermit()
    {
        $this->cacheCheck();
        $control = strtolower(request()->controller());
        $action = strtolower(request()->action());
        $module = strtolower(request()->module());
        if($module==null){$module="";}


        $roleid=session('roleid');
        $rolemenu = "//".strtolower(cache("ROLEMENU".session('roleid'))) ;
        $rolemenuall = "//".cache("ROLEMENUALL");
        $nowmenu="/".$module."/".$control."/".$action."/";

     

        if(strpos("xx/admin/index/index/",$nowmenu)>0)
        {
            return true;

        }

        if(strpos($rolemenuall,$nowmenu)>0)
        {
                    
                if (strpos($rolemenu, $nowmenu)>0) {
                    return true;
                }
                return false;
        }

        
        if(strpos($rolemenuall,$control)>0)
        {
                    
            if(strpos($rolemenu,$control)>0) //至少含有控制器
            {
                return true;
            }
    
        }
        else
        {
            return true; //没有录入菜单的控制器，一概认为有权限
        }



   

        return false;
    }
    

    function __construct() {
        parent::__construct();
    }



    /**
     * 记录日志，包括控制器、方法、网址等
     */
    private function WriteLog()
    {

        $module = \request()->module(); //获取模块层
        $controller = \request()->controller(); //获取控制器
        $action = \request()->action(); //获取方法名
        $method = \request()->method(); //获取请求方式
        $ip=\request()->ip();



        $param = [
            'controller' => $controller ,
            'action' => $action
        ];


       $name=''; //通过菜单获取
       $res= (new SysMenuModel())->getActionWhere( $param);
       if(!empty($res)){ $name=$res['title']; }
       else{
        $param['action']='index';
         $res= (new SysMenuModel())->getActionWhere( $param);
         if(!empty($res)){ $name=$res['title'].'子功能'; }
       }
       
        

        $msg='';
        if($method == 'GET'){
            $msg = '用户'.session('username').'操作了【'.$name.'】';
        }else if($method == 'POST'){
            $msg = '用户'.session('username').'编辑或者添加了【'.$name.'】';
        }

          //组装数据
          $param = [
            'username' => session('username'),
            'msg' => $msg,
            'ip' => $ip,
            'module' => $module,
            'controller' => $controller,
            'method' => $method,
            'create_time' => time(),
            'action' => $action
        ];

        (new LogActionModel())->insert($param);
    }
    


    private function cacheCheck()
    {
        $rolemnu = cache("ROLEMENU".session('roleid'));
        $roleid=session('roleid');
        if(is_null($rolemnu) || empty($rolemnu)||true){
            $roleModel = new SysRoleModel();
            $role = $roleModel->getById($roleid);

            $menmodule=new SysMenuModel();
            $menulist=doListMenu($menmodule->getListbyRoleId($roleid ));
           
            $menustr="";

            for($p=0;$p<count($menulist);$p++)
            {
                $menu=$menulist[$p];
                $menustr=$menustr.",/".$menu['module'].'/'.$menu['controller'].'/'.$menu['action']."/";
             
            }

            cache("ROLEMENU".session('roleid'),  $menustr);
        }


        $rolemenuall = cache("ROLEMENUALL");
        if (is_null($rolemenuall) || empty($rolemenuall)||true) {
            $menulist=doListMenu($menmodule->getListbyRoleId(0 ));
           
            $menustr="";

            for($p=0;$p<count($menulist);$p++)
            {
                $menu=$menulist[$p];
                $menustr=$menustr.",/".$menu['module'].'/'.$menu['controller'].'/'.$menu['action']."/";
             
            }

            cache("ROLEMENUALL",  $menustr);

        }

    }

}
